﻿using System.Globalization;
using System.Windows.Data;

namespace DimensionsHelper.Client.Converters;

public class BooleanToNumberConverter : IValueConverter, IMultiValueConverter
{

    public static BooleanToNumberConverter Instance { get; } =
        new BooleanToNumberConverter { TrueValue = 1, FalseValue = 0, IsInteger = true };

    public static BooleanToNumberConverter ReversedInstance { get; } =
        new BooleanToNumberConverter { TrueValue = 0, FalseValue = 1, IsInteger = true };

    public bool AnyTrueReturnTrue { get; set; } = true;

    public double TrueValue { get; set; }

    public double FalseValue { get; set; }

    public bool IsInteger { get; set; }

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (AnyTrueReturnTrue)
        {
            foreach (object val in values)
            {
                if (val is true)
                {
                    return GetResultValue(TrueValue);
                }
            }

            return GetResultValue(FalseValue);
        }

        foreach (object val in values)
        {
            if (val is not bool b || !b)
            {
                return GetResultValue(FalseValue);
            }
        }

        return GetResultValue(TrueValue);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        return Array.Empty<object>();
    }


    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is true)
        {
            return GetResultValue(TrueValue);
        }

        return GetResultValue(FalseValue);
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value is int i && IsInteger && i == TrueValue)
        {
            return true;
        }

        if (value is double d && !IsInteger && d == TrueValue)
        {
            return true;
        }

        return false;
    }


    private object GetResultValue(double value)
    {
        if (IsInteger)
        {
            return System.Convert.ToInt32(value);
        }

        return value;
    }
}